
--[[
	**********************
	* SvFrame - thomasfn *
	**********************
	ihook.lua - Internal hooking functionality
]]

local hooks = {}
local default = {}

--- Attaches an internal hook
-- @param event The name of the event
-- @param func The function to call
-- @param def Boolean to indicate that this should be run if all else fails.
function svr.IHook( event, func, def )
	if (def) then
		default[ event ] = func
		return
	end
	table.insert( (hooks[event] or {}), func )
end

--- Trigger the internal hooking on an event.
-- @param event The event.
-- @param ... An arbitrary number of arguments for calling the functions with.
function svr.CallIHook( event, ... )
	--print( "CALL IHOOK (" .. tostring(event) .. ")" )
	if (hooks[ event ]) then
		for id, func in pairs( hooks[ event ] ) do
			local b, res = pcall( func, ... )
			if (b and res) then return res end
			if (not b) then
				svr.Print( "IHook error (" .. event .. "): " .. res )
				table.remove( hooks[ event ], id )
			end
		end
	end
	return svr.CallIHookDef( event, ... )
end

--- Removes an internal hook.
-- @param event The event to remove the function from.
-- @param func The function to remove.
function svr.RemoveIHook( event, func )
	if (not hooks[event]) then return end
	table.removevalue( hooks[event], func )
end

--- Calling the default function for an internal hooking event
-- @param event The event.
-- @param ... Arguments to call the function with.
function svr.CallIHookDef( event, ... )
	if (default[ event ]) then
		local b, res = pcall( default[ event ], ... )
		if (not b) then
			svr.Print( "IHook error (default:" .. event .. "): " .. res )
		else
			return res
		end
	end
end